import axios from "axios";
import * as XLSX from "xlsx";
import { message } from "antd";

// 创建 axios 实例
const service = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,  // API 基础 URL
    timeout: 10000
});

let fileName = ''

// 添加请求拦截器
service.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (token) {
         config.headers.token = token
         config.headers.Authorization = token
    }

    // 处理不需要 token 的情况
    if (config.noToken) {
        delete config.headers.Authorization;
    }

    if (config.fileName) {
        fileName = config.fileName
    }

    config.headers = {
        ...config.headers,
        'Content-Type': 'application/json;application/octet-stream'  // 请求头设置
    };

    // 设置响应类型为 'blob'，确保返回的是二进制数据
    config.responseType = 'blob';

    return config;
});

// 响应拦截器
service.interceptors.response.use(response => {
    if (response.data) {
        const blob = new Blob([response.data]);
        const url = URL.createObjectURL(blob);
        fetch(url)
            .then(response => response.blob())
            .then(blobData => {
                const reader = new FileReader();
                reader.onload = function (event) {
                    const data = new Uint8Array(event.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });

                    // 获取工作簿的第一张表格
                    const sheetName = workbook.SheetNames[0];
                    const worksheet = workbook.Sheets[sheetName];
                    const html = XLSX.utils.sheet_to_html(worksheet);

                    // 创建新窗口
                    const newWindow = window.open("", "_blank", "width=800,height=600");
                    if (newWindow) {
                        // 写入 HTML 内容到新窗口
                        newWindow.document.write(`
                            <html>
            <head>
                <title>${fileName || '表格预览'}</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        margin: 20px;
                        position: relative;
                    }
                    /* 顶部容器使用 Flexbox 来居中 */
                    .header {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        width: 100%;
                        height: 50px;  /* 固定高度 */
                    }
                    h1 {
                        font-size: 20px;
                        margin: 0;
                        flex-grow: 1; /* 使标题占据可用空间并居中 */
                        text-align: center;
                    }
                    /* 右侧按钮盒子 */
                    .top-buttons {
                         position: absolute;
                         top: 10px;
                         right:20px;
                        display: flex;
                        gap: 10px;  /* 按钮之间的间距 */
                    }
                    .top-buttons button {
                        padding: 5px 10px 5px;
                        background-color: #3876f6;
                        color: white;
                        border: none;
                        cursor: pointer;
                        font-size: 14px;
                        border-radius: 8px;
                    }
                    .top-buttons button.print {
                        background-color: #fff;
                        border: 1px solid #ccc;
                        color:#333;
                    }
                    /* 表格容器 */
                    .table-container {
                        max-height: calc(100vh - 150px);  /* 让表格容器占据剩余空间，避免超出 */
                        overflow: auto;
                        margin-bottom: 20px;
                        font-size:13px;
                    }
                    table {
                        width: 100%;
                        border-collapse: collapse;
                    }
                    th, td {
                        padding: 12px 15px;   /* 增加内边距，避免挤在一起 */
                        border: 1px solid #ddd;
                        text-align: center;
                        white-space: nowrap;   /* 防止内容换行，保持在一行内 */
                    }
                    th {
                        background-color: #f2f2f2;
                        font-weight: bold;
                    }
                    /* 总条数区域 */
                    .footer {
                        display: flex;
                        justify-content: flex-end; /* 右对齐 */
                        font-size: 16px;
                        color: #555;
                    }
                </style>
                </head>
                <body>
                <div class="header">
                    <h1>${fileName || 'Excel表格预览'}</h1>
                    <div class="top-buttons">
                        <button  class="print" onclick="window.print()">打印</button>
                        <button  onclick="window.close()">关闭</button>
                    </div>
                </div>
                <div class="table-container">
                    ${html}
                </div>
                            <div class="footer">
                               <span>总条数: <span id="total-count"></span></span>
                            </div>
                            <script>
                             // 计算表格中的总条数并显示（减去标题行）
                              const tableRows = document.querySelectorAll('table tbody tr');
                              const totalCount = tableRows.length - 1;  // 减去标题行
                              document.getElementById('total-count').innerText = totalCount;
                             </script>
                          </body>
                       </html>
                        `);
                        newWindow.document.close();  // 关闭文档流
                    }
                };

                // 读取文件
                reader.readAsArrayBuffer(blobData);
            })
            .catch(error => console.error('加载 Excel 文件失败', error));
    }
    return response.data;
}, error => {
    // 处理错误
    message.error('请求失败，请重试');
    return Promise.reject(error);
});

export default service;
